﻿using SmartRS.com.vn.smartrs.dao;
using SmartRS.com.vn.smartrs.domain;
using SmartRS.com.vn.smartrs.domain.custom;
using SmartRS.com.vn.smartrs.form.menu;
using SmartRS.com.vn.smartrs.service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartRS.com.vn.smartrs.util;
using SmartRS.com.vn.smartrs.controller;
using System.Globalization;
using System.Drawing.Printing;
using log4net;
namespace SmartRS
{
    public partial class frmMain : Form
    {
        private readonly ILog log = LogManager.GetLogger("SmartRS.frmMain.cs");





        private IList<Food> listFood = null;
        private long phuPhi;
        private long giamGia;
        private int VAT;
        private long khachTra;
        private long tongTien;
        private IList<Hall> listHallSellMenu = null;

        private Account loginAccount = AccountService.getInstance().getAll()[0];
        private Desk currentDesk = DeskService.getInstance().getAll()[1];
        private int typeShowHall = ConstTypeShowHall.hall;

        private long lastDeskId = 0L;

        public frmMain()
        {
            log4net.Config.XmlConfigurator.Configure();
            InitializeComponent();
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                if (null != Session.currentBill) { fillDataBill(Session.currentBill.billId); }
                initCboTypeShowHall();
                loadHallInfo(typeShowHall);
                loadDataForSellMenu();
                loadDanhMucData();
                setEnableOnDanhMuc(false);
                setEnableOnMenu(false);
                //Load bill chagre
                fillBillReport("", new DateTime(), new DateTime(), false);
                enableBillcontrol(false);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                this.Close();
            }
        }
        #region Tab SELL
        #region list view sell menu

        //Load data form db
        private void loadDataForSellMenu()
        {
            try
            {
                Session.listFoodKindSellMenu = FoodKindService.getInstance().getAll();
                fillSellMenu(Session.listFoodKindSellMenu);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(this, "Get list food kinds happend error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new Exception("Get list food kinds happend error: " + ex.Message);
            }
        }

        //fill data for sell menu
        private void fillSellMenu(IList<FoodKind> list)
        {
            if (list != null)
            {
                lvSellMenu.Groups.Clear();
                lvSellMenu.Items.Clear();
                foreach (FoodKind fk in list)
                {
                    lvSellMenu.addGroupFoodKindToListView(fk);
                }
                //Set footer for group
                //setFooterForGroup("Bao gồm {0} món...");
                //Set collapse for listview
                lvSellMenu.SetGroupState(ListViewGroupState.Collapsible);

            }
        }
        //Search food
        private void txtTimKiem_TextChanged(object sender, EventArgs e)
        {
            try
            {
                IList<FoodKind> listFk = FoodKindController.filterFoodSellMenu(txtTimKiem.Text.Trim());

                //Fill list view
                fillSellMenu(listFk);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        //show tooltip
        private void btnFrefeshMenuSell_MouseHover(object sender, EventArgs e)
        {
            //Add tootip for component
            ToolTip ttBtnSellSearch = new ToolTip();
            ttBtnSellSearch.SetToolTip(this.btnFrefeshMenuSell, "Làm mới danh sách..");
        }
        //Get lastest data form db
        private void btnFrefeshMenuSell_Click(object sender, EventArgs e)
        {
            try
            {
                txtTimKiem.Text = "";
                loadDataForSellMenu();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        private void lvSellMenu_DoubleClick(object sender, EventArgs e)
        {
            if (null == Session.currentBill) return;

            if (lvSellMenu.SelectedItems.Count >= 1)
            {
                long foodId = 0;
                try
                {
                    //Get clicked food and call form menu to set quantity and discount
                    foodId = long.Parse(lvSellMenu.SelectedItems[0].Name);
                    Food tempFood = FoodService.getInstance().getById(foodId);
                    frmAddOrder tempFrmMenu = new frmAddOrder();
                    tempFrmMenu.sendFood(tempFood);
                    tempFrmMenu.getFoodOrder += getFoodOrder;

                    tempFrmMenu.ShowDialog();
                    if (null == Session.currentFoodOrder)
                    {
                        return;
                    }
                    FoodOrder tempFoodOrder = null;
                    //Hard code
                    bool check = FoodOrderController.checkFoodOrder(tempFood.foodId, Session.currentBill.billId, ref tempFoodOrder);
                    if (check)
                    {
                        if (null != tempFoodOrder)
                        {
                            tempFoodOrder.quantityOrder += Session.currentFoodOrder.quantityOrder;
                            try
                            {
                                if (FoodOrderService.getInstance().update(tempFoodOrder))
                                {
                                    Session.currentBill = BillService.getInstance().getById(Session.currentBill.billId);
                                    fillDataBill(Session.currentBill.billId);
                                    MessageBox.Show("Cập nhật đặt món thành công!");
                                }
                                else
                                {
                                    throw new Exception("Can not update order.");
                                }
                            }
                            catch (Exception ex1)
                            {
                                throw new Exception("Can not update order: " + ex1.Message);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            Session.currentFoodOrder.bill = Session.currentBill;
                            if (null != FoodOrderService.getInstance().insert(Session.currentFoodOrder))
                            {
                                Session.currentBill = BillService.getInstance().getById(Session.currentBill.billId);
                                fillDataBill(Session.currentBill.billId);
                                MessageBox.Show("Thêm món vào hóa đơn thành công!");
                            }
                            else
                            {
                                throw new Exception("Can not create new order.");
                            }
                        }
                        catch (Exception ex2)
                        {
                            throw new Exception("Can not create new order : " + ex2.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    MessageBox.Show("Không thể thêm món ăn vào hóa đơn!");
                }
            }
        }

        //Delegate method
        private void getFoodOrder(FoodOrder foodOrder)
        {
            Session.currentFoodOrder = foodOrder;
        }
        #endregion list view sell menu

        #region data gridview bill

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //get the food_order_id user selected
                var foodOrderId = dgvSellBill.Rows[e.RowIndex].Cells["colFoodOrderId"].Value;
                var foodOrderIdValue = (long)foodOrderId;
                Console.WriteLine("foodOrderId {0} clicked", foodOrderIdValue);

                string quantityOrderEdited = dgvSellBill.Rows[e.RowIndex].Cells["colSoLuong"].Value.ToString();
                int quantityOrderValue = Int32.Parse(quantityOrderEdited);
                Console.WriteLine("So luong {0} clicked", quantityOrderValue);
                if (quantityOrderValue <= 0)
                {
                    //go to catch when soluong < 0
                    throw new InvalidCastException("Quantity less than 0.");
                }
                else
                {
                    FoodOrder foodOrder = FoodOrderController.getFoodOrderFromListById(Session.listFoodOrder, foodOrderIdValue);
                    //update quantityOrder
                    foodOrder.quantityOrder = quantityOrderValue;
                    bool isUpdate = FoodOrderService.getInstance().update(foodOrder);
                    if (isUpdate)
                    {
                        //fill data again when update okay
                        fillDataBill(Session.currentBill.billId);
                    }
                    else
                    {
                        //go to catch when update false
                        throw new InvalidCastException();
                    }

                }

            }
            catch (Exception ice)
            {
                log.Error(ice.Message);
                MessageBox.Show("Xảy ra lỗi khi cập nhật số lượng.");
            }
            finally
            {
                //fill data again
                fillDataBill(Session.currentBill.billId);
            }

        }

        public void fillDataBill(long billId)
        {
            try
            {
                Session.listFoodOrder = FoodOrderService.getInstance().getListByBillId(billId);
                Session.billDataShow = new BillDataTable().copyProperties(Session.listFoodOrder);

            }
            catch (Exception ex)
            {
                throw new Exception("Can not load data for bill :" + ex.Message);
            }

            try
            {
                if (Session.currentBill != null)
                {

                    //Time create bill
                    lblCreateBill.Text = Session.currentBill.createDate.ToString();
                    //Vị trí
                    Hall hallInfo = HallService.getInstance().getById(Session.currentBill.desk.hall.hallId);
                    lblViTri.Text = String.Format("SẢNH {0} - BÀN {1}", hallInfo.hallName, Session.currentBill.desk.deskName);
                }
                //binding data
                dgvSellBill.DataSource = Session.billDataShow;
            }
            catch (Exception ex2)
            {
                throw new Exception("Can not set data for gridview :" + ex2.Message);
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataGridView gridView = sender as DataGridView;
            if (null != gridView)
            {
                foreach (DataGridViewRow r in gridView.Rows)
                {
                    gridView.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
                }
            }
            //Calculator price charge
            tongTien = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT);
            lblValTongTien.Text = tongTien.ToString("N0", CultureInfo.InvariantCulture);
        }

        public void addOnlyRow(long foodOrderId)
        {
            var dataFood = FoodOrderService.getInstance().getById(foodOrderId);
            //need convert food to bill show
            var dataRow = new BillDataTable().copyProperties(dataFood);
            // var hallObj = new Hall() { hallName="Sky", status=1 };
            //var hal = HallService.getInstance().insert(hallObj);
            //--------------------------------

            //   var dataRow =  new BillDataTable() {foodName = "Yen sao", foodUnit = "cai" , quantityOrder =2, discountValue = 10000, priceOrder= 4444444, priceCharge=33333333 };
            Session.billDataShow.Add(dataRow);
        }

        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
            // Ignore clicks that are not in our 
            if (e.ColumnIndex == dgvSellBill.Columns["colOption"].Index && e.RowIndex >= 0)
            {
                try
                {
                    Console.WriteLine("Button on row {0} clicked", e.RowIndex);

                    var message = "Bạn có muốn xóa order " + (e.RowIndex + 1);
                    DialogResult dialogResult = MessageBox.Show(message, "Delete order", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dialogResult == DialogResult.Yes)
                    {
                        //get the food_order_id user selected
                        var foodOrderIdSelected = dgvSellBill.Rows[e.RowIndex].Cells["colFoodOrderId"].Value;
                        var foodOrderId = (long)foodOrderIdSelected;
                        Console.WriteLine("foodOrderId {0} clicked", foodOrderId);
                        //delete database
                        //and load again
                        FoodOrder foodOrder = FoodOrderController.getFoodOrderFromListById(Session.listFoodOrder, foodOrderId);

                        bool isDel = FoodOrderService.getInstance().delete(foodOrder);
                        if (isDel)
                        {
                            fillDataBill(Session.currentBill.billId);
                        }

                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        //do something else
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Delete process happened error: " + ex.Message);
                }
            }
        }

        private void dgvSellBill_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                try
                {
                    var foodOrderIdSelected = dgvSellBill.Rows[e.RowIndex].Cells["colFoodOrderId"].Value;
                    var foodOrderId = (long)foodOrderIdSelected;
                    FoodOrder foodOrderSelected = FoodOrderService.getInstance().getById(foodOrderId);
                    frmAddOrder frmUpdateOrder = new frmAddOrder();
                    frmUpdateOrder.sendFood(foodOrderSelected.food);
                    frmUpdateOrder.getFoodOrder += getFoodOrder;
                    frmUpdateOrder.Text = "Cập nhật số lượng đặt món";

                    frmUpdateOrder.ShowDialog();
                    if (null == Session.currentFoodOrder)
                    {
                        return;
                    }

                    if (null != foodOrderSelected)
                    {
                        foodOrderSelected.quantityOrder = Session.currentFoodOrder.quantityOrder;
                        try
                        {
                            if (FoodOrderService.getInstance().update(foodOrderSelected))
                            {
                                Session.currentBill = BillService.getInstance().getById(Session.currentBill.billId);
                                fillDataBill(Session.currentBill.billId);
                                MessageBox.Show("Cập nhật số lượng thành công!");
                            }
                            else
                            {
                                MessageBox.Show("Không thể cập nhật số lượng!");
                                throw new Exception("Can not update quantity.");
                            }
                        }
                        catch (Exception ex1)
                        {
                            MessageBox.Show("Không thể cập nhật số lượng: " + ex1.Message);
                            throw new Exception("Can not update quantity.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Update quantity happened error: " + ex.Message);
                }
                finally
                {
                    Session.currentFoodOrder = null;
                }
            }
        }

        #endregion data gridview bill

        #region chuc nang sanh

        private void initCboTypeShowHall()
        {
            cboTypeShowHall.Items.Clear();
            cboTypeShowHall.Items.Add("Dạng sảnh");
            cboTypeShowHall.Items.Add("Dạng bàn");

            cboTypeShowHall.SelectedIndex = ConstTypeShowHall.desk;
        }

        private void loadHallInfo(int type)
        {
            // enable/disable text box search
            if (typeShowHall == ConstTypeShowHall.hall)
            {
                txtSearchDesk.Clear();
                txtSearchDesk.ReadOnly = true;
                txtSearchDesk.Enabled = false;
            }
            else if (typeShowHall == ConstTypeShowHall.desk)
            {
                txtSearchDesk.Clear();
                txtSearchDesk.ReadOnly = false;
                txtSearchDesk.Enabled = true;
            }

            //Get data from DB
            listHallSellMenu = HallService.getInstance().getAllOrderById();
            if (listHallSellMenu != null && listHallSellMenu.Count > 0)
            {
                // fill in lvHall
                fillHallInfo(listHallSellMenu, type);
            }
        }

        private void fillHallInfo(IList<Hall> lstHall, int type)
        {
            try
            {
                lvHall.Items.Clear();
                lvHall.Groups.Clear();

                if (type == ConstTypeShowHall.desk)
                {
                    foreach (Hall item in lstHall)
                    {
                        lvHall.addGroupHallToListView(item);
                    }

                }
                else if (type == ConstTypeShowHall.hall)
                {
                    lvHall.addHalltoListView(lstHall);
                }
                //lvHall.Sort();
            }
            catch (Exception ex)
            {
                throw new Exception("Can not fill hall info :" + ex.Message);
            }
        }

        private void updateCurrentDesk(long deskId)
        {
            try
            {
                foreach (ListViewItem item in lvHall.Items)
                {
                    item.ImageIndex = int.Parse(item.SubItems[2].Text);
                    if (item.SubItems[1].Text.Equals(deskId.ToString()))
                    {
                        item.ImageIndex = item.ImageIndex + 3;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Can not update current desk :" + ex.Message);
            }
        }


        private void transferDesk(long fromDeskId, long toDeskId, short status, long billId)
        {
            try
            {
                // change properties of from desk -> update to DB
                Desk fromD = DeskService.getInstance().getDeskById(fromDeskId);
                fromD.status = tableState.free;
                bool result = DeskService.getInstance().update(fromD);
                if (result == false)
                {
                    // update error -> log
                    MessageBox.Show("Cập nhật dữ liệu bàn thất bại.");
                    throw new Exception("Can not update data for table.");
                }

                // change properties of to desk -> update to DB
                Desk toD = DeskService.getInstance().getDeskById(toDeskId);
                toD.status = status;
                result = DeskService.getInstance().update(toD);
                if (result == false)
                {
                    // update error -> log
                    MessageBox.Show("Cập nhật dữ liệu bàn thất bại.");
                    throw new Exception("Can not update data for table.");
                }

                // change all info relate bill
                Bill bill = BillService.getInstance().getById(billId);
                bill.desk.deskId = toDeskId;
                result = BillService.getInstance().update(bill);
                if (result == false)
                {
                    // update error -> log
                    MessageBox.Show("Cập nhật dữ liệu bàn thất bại.");
                    throw new Exception("Can not update data for table.");
                }

                // load lvHall again
                loadHallInfo(typeShowHall);
                Session.currentBill = bill;
                currentDesk = toD;
                updateCurrentDesk(currentDesk.deskId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void txtSearchDesk_TextChanged(object sender, EventArgs e)
        {
            if (typeShowHall == ConstTypeShowHall.hall) { return; }
            try
            {
                IList<Hall> lstHall = filterDesk(txtSearchDesk.Text.Trim());
                fillHallInfo(lstHall, ConstTypeShowHall.desk);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show("Không thể tìm kiếm.");
            }
        }

        private void btnRefreshDeskInfo_Click(object sender, EventArgs e)
        {
            try
            {
                txtSearchDesk.Text = "";
                loadHallInfo(typeShowHall);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show("Không thể làm mới dữ liệu bàn.");
            }
        }

        private IList<Hall> filterDesk(string key)
        {
            try
            {
                IList<Hall> tempList = new List<Hall>();
                //return null if listFoodKind is null or empty
                if (listHallSellMenu == null || listHallSellMenu.Count == 0)
                {
                    return tempList;
                }

                //Filter
                foreach (Hall hall in listHallSellMenu)
                {
                    Hall tempHall = new Hall { hallId = hall.hallId, hallName = hall.hallName, deskList = new List<Desk>() };
                    foreach (Desk desk in hall.deskList)
                    {
                        //If desk name contains key --> add it to tempHall
                        if (ExtensionString.Change_AV(desk.deskName.Trim()).ToLower().Contains(ExtensionString.Change_AV(key).ToLower()))
                        {
                            tempHall.deskList.Add(desk);
                        }
                    }
                    //Add hall to list if hall's desk exists.
                    if (tempHall.deskList.Count > 0)
                    {
                        tempList.Add(tempHall);
                    }
                }

                return tempList;
            }
            catch (Exception ex)
            {
                throw new Exception("Filter desk happened error :" + ex.Message);
            }

        }

        private void lvHall_DoubleClick(object sender, EventArgs e)
        {
            if (typeShowHall == ConstTypeShowHall.hall) { return; }

            if (lvHall.SelectedItems != null && lvHall.SelectedItems.Count > 0)
            {
                try
                {

                    bool isHaveBill = false;
                    long deskId = long.Parse(lvHall.SelectedItems[0].SubItems[1].Text);
                    Desk selectedDesk = DeskService.getInstance().getById(deskId);
                    if (selectedDesk == null) { return; }

                    IList<Bill> listBill = selectedDesk.billList;

                    if (listBill != null && listBill.Count > 0)
                    {
                        foreach (Bill bill in listBill)
                        {
                            if (!bill.release)
                            {
                                isHaveBill = true;
                                Session.currentBill = bill;
                                fillDataBill(Session.currentBill.billId);
                                //update current desk
                                currentDesk = selectedDesk;
                                updateCurrentDesk(currentDesk.deskId);

                                lastDeskId = deskId;
                                break;
                            }
                        }
                    }

                    // Create new bill if don't have
                    if (!isHaveBill)
                    {
                        String message = String.Format("Bạn có muốn tạo hóa đơn mới cho bàn {0} không?",
                            selectedDesk.deskName);
                        DialogResult dialogResult = MessageBox.Show(message, "Tạo hóa đơn mới",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dialogResult == DialogResult.Yes)
                        {
                            Bill newBill = new Bill();
                            newBill.billSerial = String.Format(RSConst.BILL_SERIAL_FORMAT,
                                DateTime.Now);
                            newBill.desk = selectedDesk;
                            newBill.createDate = DateTime.Now;
                            newBill.release = false;

                            newBill = BillService.getInstance().insert(newBill);
                            Session.currentBill = newBill;
                            fillDataBill(Session.currentBill.billId);

                            selectedDesk.status = tableState.using_;
                            DeskService.getInstance().update(selectedDesk);
                            loadHallInfo(typeShowHall);
                            //update current desk
                            currentDesk = selectedDesk;
                            updateCurrentDesk(currentDesk.deskId);

                            lastDeskId = deskId;
                        }
                        else
                        {
                            //lvHall.SelectedItems[0].Focused = false;
                            ////set focus to last desk on list view Hall
                            //foreach (ListViewItem item in lvHall.Items)
                            //{
                            //    if (long.Parse(item.SubItems[1].Text) == lastDeskId)
                            //    {
                            //        //item.Focused = true;
                            //        lvHall.FocusedItem = item;
                            //        lvHall.
                            //        break;
                            //    }
                            //}
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Không thể tải hay tạo mới hóa đơn.");
                    throw new Exception("Error: " + ex.Message);
                }

            }
        }
        private void cboTypeShowHall_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboTypeShowHall.SelectedIndex != ConstTypeShowHall.hall
                && cboTypeShowHall.SelectedIndex != ConstTypeShowHall.desk) { return; }
            typeShowHall = cboTypeShowHall.SelectedIndex;
            loadHallInfo(cboTypeShowHall.SelectedIndex);
        }
        #endregion chuc nang sanh
        #endregion Tab SELL

        #region Tab MENU
        #region list danh muc
        //load data for list view danh muc
        private void loadDanhMucData()
        {
            try
            {
                Session.listFoodKindMenuDanhMuc = FoodKindService.getInstance().getAll();
                fillMenuDanhMuc();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Không thể tải dữ liệu danh mục.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new Exception("Get list food kinds for danh muc happend error: " + ex.Message);
            }
        }
        //fill data to list view danh muc
        private void fillMenuDanhMuc()
        {
            if (null != Session.listFoodKindMenuDanhMuc && Session.listFoodKindMenuDanhMuc.Count > 0)
            {
                try
                {
                    lvMenuDanhMuc.Items.Clear();
                    ListViewItem lviAll = new ListViewItem();
                    lviAll.Name = "all";

                    lviAll.ImageIndex = 0;
                    lviAll.Font = new Font(lvMenuDanhMuc.Font, FontStyle.Bold);
                    lvMenuDanhMuc.Items.Add(lviAll);
                    int count = 0;
                    foreach (FoodKind fk in Session.listFoodKindMenuDanhMuc)
                    {
                        count += fk.foodList.Count;
                        addItemDanhMuc(fk, 1);
                    }
                    lviAll.Text = string.Format("Tất cả - ({0})", count);
                }
                catch (Exception ex)
                {
                    throw new Exception("Can not fill data for list view danh muc: " + ex.Message);
                }
            }
        }
        //Add element to list view
        private void addItemDanhMuc(FoodKind foodKind, int imageIndex)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.Name = foodKind.foodKindId.ToString();
            lvi.Text = String.Format("{0} - ({1})", foodKind.foodKindName, foodKind.foodList.Count);
            lvi.ImageIndex = imageIndex;
            lvMenuDanhMuc.Items.Add(lvi);
        }

        private void lvMenuDanhMuc_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (lvMenuDanhMuc.SelectedItems.Count >= 1)
            {
                try
                {
                    //Set back color for list view item
                    setItemColorDanhMuc(lvMenuDanhMuc.SelectedItems[0], Color.Cyan);
                    if (lvMenuDanhMuc.SelectedItems[0].Name.Equals("all"))
                    {
                        Session.foodDataRow = new FoodDataRow().copyProperties(Session.listFoodKindMenuDanhMuc);
                        bindingGridMenu(Session.foodDataRow);
                        tstxtTimKiem.Text = "";
                        return;
                    }
                    long foodKindId = 0;

                    foodKindId = long.Parse(lvMenuDanhMuc.SelectedItems[0].Name);
                    FoodKind foodKind = FoodKindService.getInstance().getById(foodKindId);
                    if (foodKind != null)
                    {
                        Session.foodDataRow = new FoodDataRow().copyProperty(foodKind);
                        bindingGridMenu(Session.foodDataRow);
                        tstxtTimKiem.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
        private void bindingGridMenu(IList<FoodDataRow> data)
        {
            dgvDetail.DataSource = data;
            dgvDetail.Refresh();
        }
        //Set visible for toolstrip button on danh muc
        private void setEnableOnDanhMuc(bool state)
        {
            //Tool strip button danh muc
            tsbtnDanhMucDelete.Enabled = state;
            tsbtnDanhMucEdit.Enabled = state;
        }
        //Set visible for toolstrip button on menu
        private void setEnableOnMenu(bool state)
        {
            //Tool strip button danh muc
            tsbtnMenuDelete.Enabled = state;
            tsbtnMenuEdit.Enabled = state;
        }
        private void lvMenuDanhMuc_MouseClick(object sender, MouseEventArgs e)
        {
            if (lvMenuDanhMuc.SelectedItems.Count >= 1)
            {
                setEnableOnDanhMuc(true);
                setItemColorDanhMuc(lvMenuDanhMuc.SelectedItems[0], Color.Cyan);
            }
            else
            {
                setEnableOnDanhMuc(false);
            }
        }
        private void setItemColorDanhMuc(ListViewItem lvi, Color color)
        {
            foreach (ListViewItem listViewItem in lvMenuDanhMuc.Items)
            {
                listViewItem.BackColor = lvMenuDanhMuc.BackColor;
            }
            lvi.BackColor = color;
        }
        private void tsbtnDanhMucAdd_Click(object sender, EventArgs e)
        {
            frmAddDanhMuc tempFrm = new frmAddDanhMuc();
            tempFrm.getFoodKind += getFoodKind;
            tempFrm.ShowDialog();
            try
            {
                if (null != Session.currentFoodKind && null != FoodKindService.getInstance().insert(Session.currentFoodKind))
                {
                    refreshDanhMuc();
                    MessageBox.Show("Thêm thành công!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Thêm danh mục thất bại!");
                log.Error(ex);
            }
            finally
            {
                Session.currentFoodKind = null;
            }
        }
        private void getFoodKind(FoodKind foodKind)
        {
            Session.currentFoodKind = foodKind;
        }

        private void tsbtnDanhMucRefesh_Click(object sender, EventArgs e)
        {
            try
            {
                refreshDanhMuc();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        private void refreshDanhMuc()
        {
            try
            {
                loadDanhMucData();
                setEnableOnDanhMuc(false);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private void tsbtnDanhMucEdit_Click(object sender, EventArgs e)
        {
            if (lvMenuDanhMuc.SelectedItems.Count >= 1)
            {
                long foodKindId = 0;
                try
                {
                    foodKindId = long.Parse(lvMenuDanhMuc.SelectedItems[0].Name);
                    FoodKind fk = FoodKindService.getInstance().getById(foodKindId);
                    frmAddDanhMuc tempFrm = new frmAddDanhMuc();
                    tempFrm.Text = "Chỉnh sửa danh mục";
                    tempFrm.sendFoodKind(fk);
                    tempFrm.getFoodKind += getFoodKind;
                    tempFrm.ShowDialog();
                    try
                    {
                        if (null != Session.currentFoodKind && FoodKindService.getInstance().update(Session.currentFoodKind))
                        {
                            refreshDanhMuc();
                            MessageBox.Show("Cập nhật thành công!");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Cập nhật thất bại: " + ex.Message);
                        throw new Exception(ex.Message);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Cập nhật thành công!");
                    log.Error("Can not edit food kind ", ex);
                }
                finally
                {
                    Session.currentFoodKind = null;
                }
            }

        }
        private void tsbtnDanhMucDelete_Click(object sender, EventArgs e)
        {
            if (lvMenuDanhMuc.SelectedItems.Count >= 1)
            {
                long foodKindId = 0;
                try
                {
                    foodKindId = long.Parse(lvMenuDanhMuc.SelectedItems[0].Name);
                    Session.currentFoodKind = FoodKindService.getInstance().getById(foodKindId);
                    DialogResult result = MessageBox.Show("Bạn có chắc là muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {

                        if (FoodKindService.getInstance().delete(Session.currentFoodKind))
                        {
                            refreshDanhMuc();
                            MessageBox.Show("Xóa thành công!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Xóa thất bại!");
                    log.Error("Can not delete food kind", ex);
                }
                finally
                {
                    Session.currentFoodKind = null;
                }
            }
        }
        #endregion list danh muc

        #region grid menu
        private void fillGridDataFood(long foodKindId)
        {
            try
            {
                FoodKind foodKind = FoodKindService.getInstance().getById(foodKindId);
                listFood = foodKind.foodList;
                Session.foodDataRow = new FoodDataRow().copyProperties(listFood);

                //binding data
                dgvSellBill.DataSource = Session.billDataShow;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Tải dữ liệu món ăn thất bại.");
                throw new Exception("Can not load data for gridview food :" + ex.Message);
            }
        }
        private void dgvDetail_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvDetail.SelectedRows.Count >= 1)
            {
                setEnableOnMenu(true);
            }
            else
            {
                setEnableOnMenu(false);
            }

        }
        private void tsbtnMenuDelete_Click(object sender, EventArgs e)
        {
            if (dgvDetail.SelectedRows.Count >= 1)
            {
                try
                {
                    DialogResult result = MessageBox.Show("Bạn có chắc là muốn xóa?", "Xác nhận", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        IList<Food> tempList = new List<Food>();
                        foreach (DataGridViewRow row in dgvDetail.SelectedRows)
                        {
                            Food f = FoodService.getInstance().getById((long)row.Cells[1].Value);
                            tempList.Add(f);
                        }
                        if (FoodService.getInstance().deleteListFood(tempList))
                        {
                            //Reload danh mục và trả lại trạng thái cũ
                            ListViewItem lvi = getSelectedItemDanhMuc();
                            loadDanhMucData();
                            if (null != lvi)
                            {
                                foreach (ListViewItem lvItem in lvMenuDanhMuc.Items)
                                {
                                    if (lvItem.Name == lvi.Name)
                                    {
                                        lvItem.Selected = true;
                                        break;
                                    }
                                }
                            }
                            lvMenuDanhMuc_ItemSelectionChanged(null, null);
                            Session.currentFood = null;
                            loadDataForSellMenu();
                            MessageBox.Show("Xóa thành công!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Xóa thất bại.");
                    log.Error("Can not delete menu ", ex);
                }
            }
        }
        private void tsbtnMenuAdd_Click(object sender, EventArgs e)
        {
            frmAddMenu tempFrm = new frmAddMenu();
            tempFrm.getFood += getFood;
            tempFrm.ShowDialog();
            try
            {
                if (null != Session.currentFood)
                {
                    Session.currentFood.account = loginAccount;
                    Session.currentFood.lastUpdateTime = DateTime.Now;
                    if (null != FoodService.getInstance().insert(Session.currentFood))
                    {
                        //Reload danh mục và trả lại trạng thái cũ
                        ListViewItem lvi = getSelectedItemDanhMuc();
                        loadDanhMucData();
                        if (null != lvi)
                        {
                            foreach (ListViewItem lvItem in lvMenuDanhMuc.Items)
                            {
                                if (lvItem.Name == lvi.Name)
                                {
                                    lvItem.Selected = true;
                                    break;
                                }
                            }
                        }
                        lvMenuDanhMuc_ItemSelectionChanged(null, null);
                        loadDataForSellMenu();
                        MessageBox.Show("Thêm thành công!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Thêm thất bại.");
                log.Error("Add menu happened errors", ex);
            }
            finally
            {
                Session.currentFood = null;
            }
        }
        private void tsbtnMenuEdit_Click(object sender, EventArgs e)
        {
            if (dgvDetail.SelectedRows.Count == 1)
            {
                try
                {
                    DataGridViewRow row = dgvDetail.SelectedRows[0];
                    Food f = FoodService.getInstance().getById((long)row.Cells[1].Value);
                    frmAddMenu tempFrm = new frmAddMenu();
                    tempFrm.sendFood(f);
                    tempFrm.getFood += getFood;
                    tempFrm.ShowDialog();

                    if (null != Session.currentFood)
                    {
                        Session.currentFood.account = loginAccount;
                        Session.currentFood.lastUpdateTime = DateTime.Now;
                        if (FoodService.getInstance().update(Session.currentFood))
                        {
                            //Reload danh mục và trả lại trạng thái cũ
                            ListViewItem lvi = getSelectedItemDanhMuc();
                            loadDanhMucData();
                            if (null != lvi)
                            {
                                foreach (ListViewItem lvItem in lvMenuDanhMuc.Items)
                                {
                                    if (lvItem.Name == lvi.Name)
                                    {
                                        lvItem.Selected = true;
                                        break;
                                    }
                                }
                            }
                            lvMenuDanhMuc_ItemSelectionChanged(null, null);
                            loadDataForSellMenu();
                            MessageBox.Show("Cập nhật thành công!");
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Cập nhật thất bại!");
                    log.Error("Can not edit menu", ex);
                }
                finally
                {
                    Session.currentFood = null;
                }
            }
        }
        private void tsbtnMenuRefesh_Click(object sender, EventArgs e)
        {
            tstxtTimKiem.Text = "";
            lvMenuDanhMuc_ItemSelectionChanged(null, null);
        }
        private ListViewItem getSelectedItemDanhMuc()
        {
            if (lvMenuDanhMuc.SelectedItems.Count >= 1)
            {
                return lvMenuDanhMuc.SelectedItems[0];
            }
            return null;
        }
        private void getFood(Food food)
        {
            Session.currentFood = food;
        }

        private void dgvDetail_MouseUp(object sender, MouseEventArgs e)
        {
            if (dgvDetail.SelectedRows.Count > 1)
            {
                tsbtnMenuEdit.Enabled = false;
            }
        }

        private IList<FoodDataRow> filterFoodDataRow(string key)
        {
            try
            {
                IList<FoodDataRow> tempList = new List<FoodDataRow>();
                //return null if listfoodkind is null or empty
                if (Session.foodDataRow == null || Session.foodDataRow.Count == 0)
                {
                    return tempList;
                }

                //filter
                foreach (FoodDataRow fdr in Session.foodDataRow)
                {

                    //if food name contains key --> add it to templist
                    if (ExtensionString.Change_AV(fdr.foodName.ToLower()).Contains(ExtensionString.Change_AV(key).ToLower()))
                    {
                        tempList.Add(fdr);
                    }
                }

                return tempList;
            }
            catch (Exception ex)
            {
                throw new Exception("Can not filter menu: " + ex.Message);
            }
        }

        private void tstxtTimKiem_TextChanged(object sender, EventArgs e)
        {
            bindingGridMenu(filterFoodDataRow(tstxtTimKiem.Text.Trim()));
        }

        #endregion grid menu


        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                PrintDocument printDocument1 = new PrintDocument();

                var printerSettings = new System.Drawing.Printing.PrinterSettings();
                printerSettings.PrinterName = "Printer name";// optional
                //printerSettings.PrinterName = "HP Officejet J6400 series";

                printDocument1.PrinterSettings = printerSettings;

                printDocument1.PrintPage += printDocument1_PrintPage;
                PrintDialog printDialog1 = new PrintDialog();
                printDialog1.Document = printDocument1;
                // in the dialog, you can set up the paper size, etc.
                printDialog1.UseEXDialog = true;
                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    printDocument1.Print();
                }
            }
            catch (Exception ex)
            {
                log.Error("Can not print", ex);
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //This print form a rich textbox, but you can render pdf here.
            e.Graphics.DrawString(txtGhiChu.Text, txtGhiChu.Font, Brushes.Black, 100, 20);
            e.Graphics.PageUnit = GraphicsUnit.Inch;
        }

        //-----------------------------------------------KEY EVENT TXT BOTTOM LEFT-----------------------------------------------------------
        private void txtPhuPhi_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtGiamGia_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtTienTra_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }


        private void txtPhuPhi_TextChanged(object sender, EventArgs e)
        {
            //Reset tong tien when text change
            tongTien = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT) - giamGia;
            try
            {
                string phuPhiValue = txtPhuPhi.Text.Replace(",", "");
                if (!Util.isEmpty(phuPhiValue))
                {
                    phuPhi = Convert.ToInt64(phuPhiValue);
                    //update lable Tong Tien
                    //Calculator price charge
                    tongTien += phuPhi;
                    //txtPhuPhi.Text = phuPhi.ToString("N0", CultureInfo.InvariantCulture);
                }
                else
                {
                    phuPhi = 0;
                }

                lblValTongTien.Text = tongTien.ToString("N0", CultureInfo.InvariantCulture);
                Console.WriteLine("tong tien {0}", lblValTongTien.Text);


            }
            catch (Exception ex)
            {
                Console.WriteLine("Nhập các khoản tiền không đúng Erorr: {0}", ex);
                log.Error(ex);
                return;
            }
        }

        private void txtGiamGia_TextChanged(object sender, EventArgs e)
        {
            //Reset tong tien when text change
            tongTien = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT) + phuPhi;
            try
            {


                string giamGiaValue = txtGiamGia.Text.Replace(",", "");
                if (!Util.isEmpty(giamGiaValue))
                {
                    giamGia = Convert.ToInt64(giamGiaValue);
                    tongTien -= giamGia;
                    //txtGiamGia.Text = giamGia.ToString("N0", CultureInfo.InvariantCulture);
                }
                else
                {
                    giamGia = 0;
                }


                lblValTongTien.Text = tongTien.ToString("N0", CultureInfo.InvariantCulture);

            }
            catch (InvalidCastException ice)
            {
                Console.WriteLine("Nhập các khoản tiền không đúng Erorr: {0}", ice);
                log.Error(ice);
                return;
            }
        }

        private void txtTienTra_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string khachTraValue = txtTienTra.Text.Replace(",", "");
                if (!Util.isEmpty(khachTraValue))
                {
                    khachTra = Convert.ToInt64(khachTraValue);
                    //txtTienTra.Text = khachTra.ToString("N0", CultureInfo.InvariantCulture);
                }
                else
                {
                    khachTra = 0;
                    lblValTienThua.Text = "0";
                }
                //update label thanh toan
                lblValThanhToan.Text = khachTra.ToString("N0", CultureInfo.InvariantCulture);
                //update lable tien thua
                if (khachTra >= tongTien)
                {
                    long tienThua = khachTra - tongTien;
                    lblValTienThua.Text = tienThua.ToString("N0", CultureInfo.InvariantCulture);
                }
                else
                {
                    lblValTienThua.Text = "0";
                }


            }
            catch (InvalidCastException ice)
            {
                Console.WriteLine("Nhập các khoản tiền không đúng Erorr: {0}", ice);
                log.Error(ice);
                return;
            }
        }

        private void txtPhuPhi_Leave(object sender, EventArgs e)
        {
            tongTien = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT) + phuPhi - giamGia;
        }
        private void txtGiamGia_Leave(object sender, EventArgs e)
        {
            tongTien = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT) + phuPhi - giamGia;
        }
        //-----------------------------------------------END KEY EVENT TXT BOTTOM LEFT-----------------------------------------------------------

        private void btnThanhToan_Click(object sender, EventArgs e)
        {
            try
            {
                string message = "";
                Bill bill = BillService.getInstance().getById(1);
                //go out when bill is NULL
                if (bill == null)
                {
                    message = "Bill chưa được tạo!";
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //Cash will be get from customer
                long cashCharge = FoodOrderController.calculatorCharge(Session.listFoodOrder, VAT);
                // Customer not yet order food
                if (Session.listFoodOrder == null || Session.listFoodOrder.Count <= 0 || cashCharge < 0L)
                {
                    message = "Bill không thể thanh toán!";
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // Bill has been release
                if (bill.release)
                {
                    message = "Bill đã thanh toán rồi!";
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                //Get data user input
                try
                {
                    string phuPhiValue = txtPhuPhi.Text;
                    if (!Util.isEmpty(phuPhiValue))
                    {
                        phuPhi = Convert.ToInt64(phuPhiValue);
                    }

                    string giamGiaValue = txtGiamGia.Text;
                    if (!Util.isEmpty(giamGiaValue))
                    {
                        giamGia = Convert.ToInt64(giamGiaValue);
                    }

                    string khachTraValue = txtTienTra.Text;
                    if (!Util.isEmpty(khachTraValue))
                    {
                        khachTra = Convert.ToInt64(khachTraValue);
                    }

                }
                catch (InvalidCastException ice)
                {
                    Console.WriteLine("Nhập các khoản tiền không đúng Erorr: {0}", ice);
                    message = "Các khoản tiền không hợp lệ!\nBill không thể thanh toán!";
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("Value is invalid :" + ice.Message);
                }


                //when customer not paid enghout
                if (khachTra <= 0L || khachTra < cashCharge)
                {
                    message = "Khách chưa trả đủ tiền\nBill không thể thanh toán!";
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //update data bill
                bill.cashTotal = FoodOrderController.calculatorBasePrice(Session.listFoodOrder);
                //update cash charge cutomer
                bill.cashCharge = cashCharge;
                bill.discountValue = giamGia;
                //update cash receive from customer
                bill.cashReceive = khachTra;
                //update cash return for customer
                bill.cashReturn = khachTra - cashCharge;
                //update date output billl => now()
                bill.outputDate = DateTime.Now;
                //update bill status => free
                bill.release = true;
                //update desk status => free
                bill.desk.status = 0;

                //update when cash > 0
                message = String.Format("Bạn có muốn thanh toán bill của bàn {0}", bill.desk.deskName);
                DialogResult dialogResult = MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    //update bill in DB
                    bool isUpdate = BillService.getInstance().update(bill);
                    //upadte successfull
                    if (isUpdate)
                    {
                        //udpate TextBox bottom left
                        txtPhuPhi.Text = "";
                        txtGiamGia.Text = "";
                        txtTienTra.Text = "";
                        //udpate desk status in screm
                        loadHallInfo(typeShowHall);
                        message = String.Format("Bill của bàn {0} đã thanh toán thành công!", bill.desk.deskName);
                    }
                    //update fail
                    else
                    {
                        message = String.Format("Bill của bàn {0} đã thanh toán thất bại!", bill.desk.deskName);
                    }
                    //show message box
                    MessageBox.Show(message, "Thanh Toán", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void btnChuyenBan_Click(object sender, EventArgs e)
        {
            frmTransferDesk frm = new frmTransferDesk(currentDesk.deskId, listHallSellMenu);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                transferDesk(currentDesk.deskId, frm.destDeskId, currentDesk.status, Session.currentBill.billId);
                MessageBox.Show("Tranfer thanh cong");
            }
        }
        private void btnGhepHoaDon_Click(object sender, EventArgs e)
        {
            frmJoinDesk frm = new frmJoinDesk();

            frm.assignData(currentDesk);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                //transferDesk(currentDesk.deskId, frm.destDeskId, currentDesk.status, currentBill.billId);
                MessageBox.Show("Tranfer thanh cong");
            }
        }

        #endregion Tab SELL

        //----------------------------------------------------------------------------------------------------------
        #region TAB BILL
        public void fillBillReport(string serial, DateTime start, DateTime end, bool isUseDate)
        {
            try
            {
                BillController.getBillDataForGridviewReport(serial, start, end, isUseDate);
                bindingBillReport(Session.billReportDataShow);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Load bill report fail with error : {0}", ex);
                throw new Exception("Can not fill data bill " + ex.Message);
            }
        }

        private void bindingBillReport(IList<BillReportDataRow> data)
        {
            dgvBillReport.DataSource = data;
            dgvBillReport.Refresh();
        }
        public void BillReportMonthly()
        {
            //IList<Bill> listBill = BillService.getInstance().getAll();

        }


        

        private void dgvBillReport_DataSourceChanged(object sender, EventArgs e)
        {
            try
            {
                long billCount = 0;
                long cashSum = 0;
                BillController.sumarizeBill(Session.billReportDataShow, ref billCount, ref cashSum);
                lbBillSumVal.Text = billCount.ToString();
                lbChargeSumVal.Text = cashSum.ToString();
            }
            catch(Exception ex)
            {
                log.Error("Can not sumarize data bill", ex);
            }
        }

        private void enableBillcontrol(bool state)
        {
            tsbtnBillDetail.Enabled = state;
            tsbtnBillDelete.Enabled = state;
            tsbtnBillPrint.Enabled = state;
        }


        private void dgvBillReport_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvBillReport.SelectedRows.Count >= 1)
            {
                enableBillcontrol(true);
            }
            else
            {
                enableBillcontrol(false);
            }
        }
        

        private void dgvBillReport_MouseUp(object sender, MouseEventArgs e)
        {
            if (dgvBillReport.SelectedRows.Count > 1)
            {
                tsbtnBillDetail.Enabled = false;
            }
        }


        private void dtpStartTime_Validated(object sender, EventArgs e)
        {
            if (dtpStartTime.Value > dtpEndTime.Value)
            {
                MessageBox.Show("Thời gian bắt đầu không thể lớn hơn thời gian kết thúc!\r\nVui lòng chọn lại.....");
                dtpStartTime.Value = Session.billReportStartDate;
            }
            else
            {
                Session.billReportStartDate = dtpStartTime.Value;
            }
        }

        private void dtpEndTime_Validated(object sender, EventArgs e)
        {
            if (dtpEndTime.Value < dtpStartTime.Value)
            {
                MessageBox.Show("Thời gian kết thúc không thể bé hơn thời gian bắt đầu!\r\nVui lòng chọn lại.....");
                dtpEndTime.Value = Session.billReportEndDate;
            }
            else
            {
                Session.billReportEndDate = dtpEndTime.Value;
            }
        }
        #endregion TAB BILL

        private void mcBillDate_DateSelected(object sender, DateRangeEventArgs e)
        {
            try
            {
                fillBillReport("", mcBillDate.SelectionStart, mcBillDate.SelectionStart, true);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Không thể tải dữ liệu hóa đơn!");
                log.Error("Can not get data for bill report", ex);
            }
        }
        //----------------------------------------------------------------------------------------------------------


    }
}

